
#include "comm.hpp"

// 创建命名管道,客户端作为写端以open(PATH,O_WRONLY)打开管道文件
// 服务端作为读端以open(PATH,O_RDONLY)方式打开同一个管道文件
// open()函数打开文件成功返回文件描述符,失败返回-1
int main()
{
    Fifo fifo(PATH);
    cout << "I am Server!" << endl;
    int rfd = open(PATH, O_RDONLY);
    if (rfd < 0)
    {
        cerr << "open file failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        return 1;
    }
    cout << "open file success" << endl;
    // 读取命名管道中的内容
    char buffer[1024];
    while (true)
    {
        // 假定客户端发送字符串
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            // 读取成功，返回实际读取到的字节个数
            buffer[n] = '\0';
            cout << "client send message:" << buffer << endl;
        }
        else if (n == 0)
        {
            // 读取到管道文件末尾,没有内容可以读取
            cout << "client quit, server quitting!!" << endl;
            break;
        }
        else
        {
            //读取失败,返回-1
            cerr << "read failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
            break;
        }
    }
    close(rfd);
    return 0;
}